<template>
  <span id="info-container" @click.stop="openInfoDialog">
    <span class="user-name">hello, {{ userInfo.userName }}</span>
    <el-drawer :visible.sync="visible" size="500px" append-to-body :before-close="handleClose">
        <div id="info-box">
        <!--  名称栏  -->
        <h1 style="width: 100%; text-align: center;">{{ userInfo.userName }}
          <el-button size="medium" type="text" class="el-icon-edit" @click="() => editDrawer = true"/>
          <el-drawer
              title="编辑信息"
              size="500px"
              :append-to-body="true"
              :before-close="() => editDrawer = false"
              :visible.sync="editDrawer">
            <div style="width: 100%; display: flex; justify-content: center">
              <el-form ref="userInfoForm" :model="userInfoForm" label-width="80px" :rules="rules">
                <el-form-item label="用户名" prop="userName">
                  <el-input v-model="userInfoForm.userName" placeholder="请输入用户名"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userInfoForm.email" placeholder="请输入邮箱"/>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userInfoForm.phone" placeholder="请输入手机号"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateInfo">修改</el-button>
                  <el-button type="info" @click="resetForm('userInfoForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
        </el-drawer>
        </h1>
      </div>

      <!--  底部  -->
      <div style="display: flex; justify-content: center;">
        <el-button type="text" @click.stop="() => passDrawer = true">修改密码</el-button>
        <el-drawer
            title="修改密码"
            size="500px"
            :append-to-body="true"
            :before-close="() => passDrawer = false"
            :visible.sync="passDrawer">
            <div style="width: 100%; display: flex; justify-content: center">
              <el-form ref="passForm" :model="passForm" label-width="80px" :rules="rules">
                <el-form-item label="旧密码" prop="oldPass">
                  <el-input type="password" show-password v-model="passForm.oldPass" placeholder="请输入旧密码"/>
                </el-form-item>
                <el-form-item label="新密码" prop="pass">
                  <el-input type="password" show-password v-model="passForm.pass" placeholder="请输入新密码"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changePass">修改</el-button>
                  <el-button type="info" @click="resetForm('passForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
        </el-drawer>
        <span style="width: 1px; height: 38px; background-color: var(--theme-color); margin: 0 10px; opacity: 0.5"/>
        <el-button type="text" @click.stop="loginOut">退出登录</el-button>
      </div>
    </el-drawer>
  </span>
</template>
<script>
import {removeToken} from "@/util/auth";
import {changePass, currentUser, update} from "@/api/userApi";

export default {
  name: "infoBox",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        // 校验密码格式（至少8位数，包含大小写字母）
        if (!/^(?=.*[a-z])(?=.*[A-Z]).{8,}$/.test(value)) {
          callback(new Error('密码至少8位数，包含大小写字母'));
        }
        callback();
      }
    };
    return {
      visible: false,
      editDrawer: false,
      passDrawer: false,
      userInfo: {},
      userInfoForm: {},
      passForm: {},
      rules: {
        userName: [
          {required: false, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 155, message: '长度在 1 到 255 个字符', trigger: 'blur'}
        ],
        email: [
          {required: false, message: '请输入邮箱', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        phone: [
          {required: false, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        oldPass: [
          {required: true, message: '请输入旧密码', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {
    // 获取用户信息
    init() {
      currentUser().then(res => {
        this.userInfo = res.data
        this.userInfoForm = {
          userName: this.userInfo.userName,
          email: this.userInfo.email,
          phone: this.userInfo.phone
        }
      })
    },
    // 修改信息
    updateInfo() {
      this.$refs.userInfoForm.validate(valid => {
        if (!valid) return
        if (!this.userInfoForm) {
          update(this.userInfoForm).then(() => {
            this.$message.success('修改成功')
            this.editDrawer = false
            this.init()
          })
        }
      })
    },
    // 修改密码
    changePass() {
      this.$refs.passForm.validate(valid => {
        if (!valid) return
        if (!this.passForm) {
          changePass(this.passForm).then(() => {
            this.$message.success('修改成功')
            this.passDrawer = false
            this.loginOut()
          })
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    loginOut() {
      removeToken()
      this.$emit('flashNavBox')
      this.handleClose()
      // 返回首页
      this.$router.push('/')
    },
    openInfoDialog() {
      this.visible = true
    },
    handleClose() {
      this.visible = false
    }
  },
  mounted() {
    this.init()
  }
}
</script>


<style scoped lang="scss">
#info-container {
  height: 100%;
  cursor: pointer;

  .user-name {
    font-size: small;
  }
}

#info-box {
  width: 100%;
  height: 90%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .line-center {
    width: 100%;
    display: flex;
    justify-content: center;
  }
}
</style>